<template>
  <div class="data-table-container layout-padding">
    <el-card class="layout-padding-auto" shadow="hover">
      <el-form ref="queryFormRef" :model="state.tableData.param.dataObj" inline>
        <el-form-item class="!mr-4" prop="fileName">
          <el-input v-model="state.tableData.param.dataObj.fileName" class="max-w-180px" clearable
                    placeholder="请输入文件名"
                    size="default">
          </el-input>
        </el-form-item>
        <el-form-item class="!mr-4" prop="originalName">
          <el-input v-model="state.tableData.param.dataObj.originalName" class="max-w-180px" clearable
                    placeholder="请输入原名"
                    size="default">
          </el-input>
        </el-form-item>
        <el-form-item class="!mr-4" prop="fileSuffix">
          <el-input v-model="state.tableData.param.dataObj.fileSuffix" class="max-w-180px" clearable
                    placeholder="请输入文件后缀名"
                    size="default">
          </el-input>
        </el-form-item>
        <el-form-item v-auth="'oss.list'" class="!mr-4">
          <el-button size="default" type="primary" @click="getTableData">
            <el-icon>
              <ele-Search/>
            </el-icon>
            查询
          </el-button>
        </el-form-item>
        <el-form-item v-auth="'oss.list'" class="!mr-4">
          <el-button size="default" type="primary" @click="onHandleResetFields">
            <el-icon>
              <ele-Refresh/>
            </el-icon>
            重置
          </el-button>
        </el-form-item>
        <el-form-item v-auth="'oss.export'" class="!mr-4">
          <el-button
              size="default"
              type="warning"
              @click="handleExport"
          >
            <el-icon>
              <ele-Download/>
            </el-icon>
            导出
          </el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col v-auth="'oss.upload'" :span="1.5">
          <el-button
              plain
              size="default"
              type="primary"
              @click="handleFile"
          >
            <el-icon>
              <ele-Upload/>
            </el-icon>
            上传文件
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
              plain
              size="default"
              type="primary"
              @click="handleImage"
          >
            <el-icon>
              <ele-Upload/>
            </el-icon>
            上传图片
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
              :type="previewListResource ? 'danger' : 'warning'"
              plain
              size="default"
              @click="handlePreviewListResource(!previewListResource)"
          >预览开关 : {{ previewListResource ? "禁用" : "启用" }}
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
              plain
              size="default"
              type="info"
              @click="handleOssConfig"
          >
            <el-icon>
              <ele-Operation/>
            </el-icon>
            配置管理
          </el-button>
        </el-col>
      </el-row>
      <el-table v-loading="state.tableData.loading" :data="state.tableData.data">
        <el-table-column label="序号" type="index" width="60"/>
        <el-table-column label="文件名" prop="fileName"/>
        <el-table-column label="原名" prop="originalName"/>
        <el-table-column align="center" label="文件后缀" prop="fileSuffix"/>
        <el-table-column align="center" label="文件展示" prop="url">
          <template #default="scope">
            <ImagePreview
                v-if="previewListResource && checkFileSuffix(scope.row.fileSuffix)"
                :height=100
                :preview-src-list="[scope.row.url]"
                :src="scope.row.url"
                :width=100
            />
            <span v-if="!checkFileSuffix(scope.row.fileSuffix) || !previewListResource"
                  v-text="scope.row.url"/>
          </template>
        </el-table-column>
        <el-table-column align="center" label="创建时间" prop="createTime" sortable="custom" width="180"/>
        <el-table-column align="center" label="上传人" prop="createBy"/>
        <el-table-column align="center" label="服务商" prop="service"
                         sortable="custom"/>
        <el-table-column label="操作" width="250">
          <template #default="scope">
            <el-button
                icon="el-icon-edit"
                size="default"
                type="text"
                @click="handleDownload(scope.row)"
            >下载
            </el-button>
            <el-button v-auth="'oss.del'" size="default" text
                       type="danger" @click="onRowDel(scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination v-model:current-page="state.tableData.param.pageNum"
                     v-model:page-size="state.tableData.param.pageSize" :page-sizes="[10, 20, 30]" :pager-count="5"
                     :total="state.tableData.total" background class="mt15"
                     layout="total, sizes, prev, pager, next, jumper"
                     @size-change="onHandleSizeChange" @current-change="onHandleCurrentChange">
      </el-pagination>
    </el-card>


    <!-- 添加或修改OSS对象存储对话框 -->
    <el-dialog v-model="state.open" :title="state.title" append-to-body width="500px">
      <el-form :model="state.form" label-width="80px">
        <el-form-item label="文件名">
          <fileUpload v-if="state.type === 0" v-model="state.form.file"/>
          <imageUpload v-if="state.type === 1" v-model="state.form.file"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="state.buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" name="sysOss" setup>
import {onMounted, reactive, ref} from 'vue';
import {ElLoading, ElMessage, ElMessageBox} from 'element-plus';
import {sysNoticeApi} from "/@/api/sys/notice";
import {download} from "/@/utils/seeTools";
import {configApi} from "/@/api/sys/config";
import {ossApi} from "/@/api/sys/oss";
import {useRouter} from 'vue-router';

// 定义变量内容
const router = useRouter();
const previewListResource = ref();
const state = reactive<any>({
  tableData: {
    data: [],
    total: 0,
    loading: false,
    param: {
      pageNum: 1,
      pageSize: 10,
      dataObj: {
        fileName: '',
        originalName: '',
        fileSuffix: '',
        service: '',
      },
    },
  },
  buttonLoading: false,
  title: '',
  open: false,
  type: 0,
  form: {
    file: '',
  }
});

// 初始化表格数据
const getTableData = () => {
  state.tableData.loading = true;
  configApi()
      .getConfigKey("sys.oss.previewListResource")
      .then(res => {
        previewListResource.value = res.data.configValue === 'true';
      })
  ossApi()
      .listOss(state.tableData.param)
      .then((res) => {
        state.tableData.data = res.data.records;
        state.tableData.total = res.data.total;
        state.tableData.loading = false;
      })
      .catch(() => {
        state.tableData.loading = false;
      });
};
// 删除用户
const onRowDel = (row: any) => {
  ElMessageBox.confirm(`此操作将永久删除账户“${row.originalName}”，是否继续?`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    ossApi()
        .delOss(row)
        .then(() => {
          getTableData();
          ElMessage.success('删除成功');
        });
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};
// 分页改变
const onHandleSizeChange = (val: number) => {
  state.tableData.param.pageSize = val;
  getTableData();
};
// 分页改变
const onHandleCurrentChange = (val: number) => {
  state.tableData.param.pageNum = val;
  getTableData();
};
// 页面加载时
onMounted(() => {
  getTableData();
});
// 重置查询表单
const onHandleResetFields = () => {
  queryFormRef.value.resetFields();
  getTableData();
};

// 预览列表图片状态修改
const handlePreviewListResource = (previewListResource: any) => {
  let text = previewListResource ? "启用" : "停用";
  ElMessageBox.confirm('确认要"' + text + '""预览列表图片"配置吗?').then(() => {
    return configApi().updateConfigByKey("sys.oss.previewListResource", previewListResource)
  }).then(() => {
    getTableData();
    ElMessage.success(text + "成功");
  }).catch(() => {
  })
}

/** 任务日志列表查询 */
const handleOssConfig = () => {
  router.push({path: '/system/oss-config'})
}

const checkFileSuffix = (fileSuffix: any) => {
  let arr = ["png", "jpg", "jpeg"];
  return arr.some(type => {
    return fileSuffix.indexOf(type) > -1;
  });
}

const handleFile = () => {
  reset();
  state.open = true;
  state.title = "上传文件";
  state.type = 0;
}

const handleImage = () => {
  reset();
  state.open = true;
  state.title = "上传图片";
  state.type = 1;
}

const cancel = () => {
  state.open = false
  reset();
}

const submitForm = () => {
  state.open = false;
  getTableData();
}

const reset = () => {
  state.form.file = undefined;
}

const handleDownload = (row: any) => {
  let downloadLoadingInstance = ElLoading.service({
    text: "正在下载文件，请稍候",
    spinner: "el-icon-loading",
    background: "rgba(0, 0, 0, 0.7)",
  })
  sysNoticeApi()
      .downloadRecord(row.id)
      .then(res => {
        download(res, row.originalName);
        downloadLoadingInstance.close();
      })
}

const handleExport = () => {
  let downloadLoadingInstance = ElLoading.service({
    text: "正在导出数据，请稍候",
    spinner: "el-icon-loading",
    background: "rgba(0, 0, 0, 0.7)",
  })
  sysNoticeApi()
      .exportRecord(state.tableData.param.params)
      .then(res => {
        download(res, '通知公告表.xlsx');
        downloadLoadingInstance.close();
      })
}
</script>
